package com.sdry.web.controller.permission;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.base.Joiner;
import com.sdry.entity.permission.UpmsRole;
import com.sdry.entity.permission.UpmsRolePermission;
import com.sdry.service.permission.UpmsRolePermissionService;
import com.sdry.service.permission.UpmsRoleService;
import com.sdry.utils.DateJsonValueProcessor;
import com.sdry.utils.ResponseUtil;
/**
*
* @ClassName:UpmsRoleController
* @Description:角色
* @Author tdd
* @Date Mon Jul 30 15:18:29 CST 2018
* @version 1.0
*/
@Controller
@RequestMapping("/upmsRole")
public class RoleController{
   /**注入角色Server*/
   @Resource UpmsRoleService  upmsRoleService;
   /**注入角色+权限Server*/
   @Resource UpmsRolePermissionService  upmsRolePermissionService;
   /**
    * 条件分页查询
    * @param upmsRole 角色实体类
    * @param response
    * @return
    * @throws Exception
    */
   @RequestMapping("/list")
   public String list(UpmsRole upmsRole,HttpServletResponse response) throws Exception{
   	/*
   	* 条件分页查询内容
   	*/
   	List<UpmsRole> list = upmsRoleService.findPageByMution(upmsRole);
   	/*
   	* 条件查询总条数
   	*/
   	Integer total = upmsRoleService.selectCountByMution(upmsRole);

   	/*
   	* 转为json数据传至页面
   	*/
   	JsonConfig jsonConfig = new JsonConfig();
   	jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
   	//创建result
   	JSONObject result = new JSONObject();
   	//转json数据
   	JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
   	//添加入result
   	result.put("rows", jsonArray);
   	result.put("total", total);
   	//发送result
   	ResponseUtil.write(response, result);
   	return null;
   }
   /**
    * 添加角色
    * @param upmsRole 角色实体类
    * @param session
    * @param response
    * @return
    * @throws Exception
   */
   @RequestMapping("/add")
   public void add(Long[] permissionIds, UpmsRole upmsRole,HttpSession session, HttpServletResponse response) throws Exception{
       /*
        * 添加返回id
       */
	   SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
       String   date   =   sDateFormat.format(new Date());
       upmsRole.setCtime(date);
       Long id = upmsRoleService.insert(upmsRole);
       if (null != id) {
    	   for (int i = 0; i < permissionIds.length; i++) {
	    		UpmsRolePermission param = new UpmsRolePermission();
	    		param.setRoleId(id);
	    		param.setPermissionId(permissionIds[i]);
				upmsRolePermissionService.insert(param);
    	   }
           response.getWriter().print("1");
       }else{
           response.getWriter().print("0");
       }
   }
   /**
    * 多删除
    * @param ids 角色id累加字符串
    * @param session
    * @param response
    * @return
    * @throws Exception
   */
   @RequestMapping("/delete")
   public void delete(String ids,HttpSession session, HttpServletResponse response) throws Exception{
       System.out.println(ids);
       ids=ids.replace("'",""); 
       /*
        * 多删除返回影响行数
       */
       Integer count = upmsRoleService.delete(ids);
       if (count >= 1) {
           response.getWriter().print("1");
       }else{
           response.getWriter().print("0");
       }
   }
   /**
    * 条件查询角色
    * @param upmsRole 角色实体类
    * @return 角色实体类集合
   */
   @RequestMapping("/queryAll")
   @ResponseBody
   public List<UpmsRole> queryAllByMution(UpmsRole upmsRole){
       List<UpmsRole> list = upmsRoleService.queryAllByMution(upmsRole);
       return list;
   }
   /**
    * 根据id查角色
    * @param id 角色id
    * @return 角色实体类
   */
   @RequestMapping("/queryById")
   @ResponseBody
   public UpmsRole queryById(Long id){
       UpmsRole upmsRole = upmsRoleService.queryById(id);
       return upmsRole;
   }
   /**
    * 修改部门
    * @param upmsRole 角色实体类
    * @param session
    * @param response
    * @return
    * @throws Exception
   */
   @RequestMapping("/update")
   public void update(Long[] permissionIds,UpmsRole upmsRole,HttpSession session, HttpServletResponse response) throws Exception{
       /*
        * 修改返回影响行数
       */
       Integer count = upmsRoleService.update(upmsRole);
       if (count >= 1) {
    	   UpmsRolePermission param = new UpmsRolePermission();
    	   param.setRoleId(upmsRole.getRoleId());
    	   List<UpmsRolePermission> queryAllByMution = upmsRolePermissionService.queryAllByMution(param);
    	   //原有的权限id
    	   List<Long> list = new ArrayList<>();
           //原有的权限id对应角色+权限id
            List<Long> listid = new ArrayList<>();
			for (int i = 0; i < queryAllByMution.size(); i++) {
				list.add(queryAllByMution.get(i).getPermissionId());
                listid.add(queryAllByMution.get(i).getRolePermissionId());

			}
    	   //需要添加的权限id
		   List<Long> addList = new ArrayList<>();
		   for (int i = 0; i < permissionIds.length; i++) {
			   //原有的权限id不包含该修改权限id
			   if(!list.contains(permissionIds[i])){
				   addList.add(permissionIds[i]);
			   }
		   }
    	   //添加权限
    	   for (int j = 0; j < addList.size(); j++) {
    		   param.setPermissionId(addList.get(j));
    		   upmsRolePermissionService.insert(param);
    	   }
    	   //需要删除的权限id
    	   List<Long> deleteList = new ArrayList<>();
		   for (int j = 0; j < list.size(); j++) {
			   //修改的权限id不包含该原有权限id
			   if(!Arrays.asList(permissionIds).contains(list.get(j))){
				   deleteList.add(listid.get(j));
			   }
		   }
    	   //删除
    	   String ids = Joiner.on(",").join(deleteList);
		   upmsRolePermissionService.delete(ids);
    	   
           response.getWriter().print("1");
       }else{
           response.getWriter().print("0");
       }
   }
}
